package cn.kshell.druid.spring.boot.autoconfigure;

import cn.kshell.druid.spring.boot.filter.CommonJsFilter;
import cn.kshell.druid.spring.boot.filter.HeaderHtmlFilter;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

/**
 * 过滤Druid Monitor中的广告
 *
 * @author kshell
 */
@Configuration
@ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true)
public class RemoveDruidAdAutoConfiguration {

    private FilterRegistrationBean build(DruidStatProperties properties, String url, Filter filter) {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        pattern = pattern.replaceAll("\\*", url);

        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.addUrlPatterns(pattern);
        registrationBean.setFilter(filter);
        return registrationBean;
    }

    /**
     * 过滤掉common.js中的广告
     *
     * @param properties DruidStatProperties
     * @return FilterRegistrationBean
     */
    @Bean
    @ConditionalOnBean(DruidStatProperties.class)
    public FilterRegistrationBean removeDruidCommonAd(DruidStatProperties properties) {
        final String url = "js/common.js";
        Filter filter = new CommonJsFilter();

        return this.build(properties, url, filter);
    }

    /**
     * 过滤掉header.html中的wiki链接
     *
     * @param properties DruidStatProperties
     * @return FilterRegistrationBean
     */
    @Bean
    @ConditionalOnBean(DruidStatProperties.class)
    public FilterRegistrationBean removeDruidHeaderAd(DruidStatProperties properties) {
        final String url = "header.html";
        Filter filter = new HeaderHtmlFilter();

        return this.build(properties, url, filter);
    }
}
